package tech.yangzhijie.basic.knowledge.mianshi;

import java.util.concurrent.CountDownLatch;

/**
 * Volatile不保证原子性
 */
public class Test02Volatile {

    public static void main(String[] args) {
        MyData02 myData02 = new MyData02();
        CountDownLatch countDownLatch = new CountDownLatch(20);

        for (int i = 1; i <= 20; i++) {
            new Thread(()->{
                try {
                    for (int j=1;j <= 1000;j++){
                        myData02.increasing();
                    }
                }finally {
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(myData02.num);
    }
}

class MyData02 {
    volatile int num = 0;

    public void increasing(){
        this.num++;
    }
}
